package org.wanda.pv.service.file.impl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;
import org.nutz.dao.Dao;
import org.nutz.filepool.NutFilePool;
import org.nutz.img.Images;
import org.nutz.lang.Files;
import org.nutz.lang.random.R;
import org.nutz.lang.util.Disks;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.wanda.pv.config.FileProperties;
import org.wanda.pv.model.file.FileUploadInfo;
import org.wanda.pv.service.BaseServiceImpl;
import org.wanda.pv.service.file.FileUploadService;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.*;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class FileUploadServiceImpl extends BaseServiceImpl<FileUploadInfo> implements FileUploadService {
    private final Log log = LogFactory.getLog(this.getClass());


    Document document = null;
    @Autowired
    public FileUploadServiceImpl(Dao dao) {
        super(dao);
    }

    @Autowired
    private FileProperties properties;

    @Autowired
    Dao dao;

    @Autowired
    private NutFilePool tempFilePool;


    // inputStream转outputStream
    public ByteArrayOutputStream parse(final InputStream in) throws Exception {
        final ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        int ch;
        while ((ch = in.read()) != -1) {
            swapStream.write(ch);
        }
        return swapStream;
    }

    @Override
    public Map<String, Object> pdf2Thumbnail(String imgUrl) throws Exception {
        FileUploadInfo fileUploadInfo = new FileUploadInfo();
        Map<String, Object> result = new HashMap<>();


            float rotation = 0f;
            //缩略图显示倍数，1表示不缩放，0.5表示缩小到50%
            float zoom = 0.3f;
            URL url =  new URL(imgUrl);
            document = new Document();
            document.setUrl(url);
            BufferedImage image = (BufferedImage)document.getPageImage(0, GraphicsRenderingHints.SCREEN,
                    Page.BOUNDARY_CROPBOX, rotation, zoom);

            Iterator iter = ImageIO.getImageWritersBySuffix("jpg");
            ImageWriter writer = (ImageWriter)iter.next();

            //
            String thumbnailFileName =  getPath()+File.separator+System.currentTimeMillis()+".jpg";
            File thumbnailFile = new File(thumbnailFileName);
            FileOutputStream out = new FileOutputStream(thumbnailFile);
            ImageOutputStream outImage = ImageIO.createImageOutputStream(out);

            writer.setOutput(outImage);
            image = Images.zoomScale(image, 280, 250);  //压缩图为 280 * 250
            writer.write(new IIOImage(image, null, null));


            // 将转化成的数据存到file表中
        fileUploadInfo.setServerPath(thumbnailFile.getAbsolutePath());
            fileUploadInfo.setExName("jpg");
            fileUploadInfo = dao.insert(fileUploadInfo);
            result.put("tfid",fileUploadInfo.getId());

       // writer.reset();
        image.flush();
        image=null;
        document.dispose();

        return result;
    }

    @Override
    public Map<String, Object> pdf2Thumbnail_(String filePath) throws Exception {
        FileUploadInfo fileUploadInfo = new FileUploadInfo();
        Map<String, Object> result = new HashMap<>();


        float rotation = 0f;
        //缩略图显示倍数，1表示不缩放，0.5表示缩小到50%
        float zoom = 0.3f;
        document = new Document();
        document.setFile(filePath);
        BufferedImage image = (BufferedImage)document.getPageImage(0, GraphicsRenderingHints.SCREEN,
                Page.BOUNDARY_CROPBOX, rotation, zoom);

        Iterator iter = ImageIO.getImageWritersBySuffix("jpg");
        ImageWriter writer = (ImageWriter)iter.next();

        //
        String thumbnailFileName =  getPath()+File.separator+System.currentTimeMillis()+".jpg";
        File thumbnailFile = new File(thumbnailFileName);
        FileOutputStream out = new FileOutputStream(thumbnailFile);
        ImageOutputStream outImage = ImageIO.createImageOutputStream(out);

        writer.setOutput(outImage);
        image = Images.zoomScale(image, 280, 250);  //压缩图为 280 * 250
        writer.write(new IIOImage(image, null, null));


        // 将转化成的数据存到file表中
        fileUploadInfo.setServerPath(thumbnailFile.getAbsolutePath());
        fileUploadInfo.setExName("jpg");
        fileUploadInfo = dao.insert(fileUploadInfo);
        result.put("tfid",fileUploadInfo.getId());

        // writer.reset();
        image.flush();
        image=null;
        document.dispose();

        return result;
    }

    @Override
    public Map<String, Object> pdf2jpg(String imgUrl) throws Exception {
        FileUploadInfo fileUploadInfo = new FileUploadInfo();
        Map<String, Object> result = new HashMap<>();
        try {
            float rotation = 0f;
            //缩略图显示倍数，1表示不缩放，0.5表示缩小到50%
            float zoom = 2.0f;
            String suffix = Files.getSuffix(imgUrl);
            System.out.println(suffix);
            URL url =  new URL(imgUrl);
            String[] split = url.getPath().split("/");
            String fileName = split[split.length - 1];
            System.out.println("fileName:"+fileName);
            document = new Document();
            document.setUrl(url);
            BufferedImage image = (BufferedImage)document.getPageImage(0, GraphicsRenderingHints.SCREEN,
                    Page.BOUNDARY_CROPBOX, rotation, zoom);
            RenderedImage rendImage = image;
            String thumbnailFileName =  getPath()+File.separator+System.currentTimeMillis()+".jpg";
            File thumbnailFile = new File(thumbnailFileName);
            ImageIO.write(rendImage, "jpg", thumbnailFile);

            int width = image.getWidth();
            int height = image.getHeight();
            System.out.println("width:::"+width);
            System.out.println("height:::"+height);

            String absolutePath = thumbnailFile.getAbsolutePath();
            System.out.println(absolutePath);

            // 将转化成的数据存到file表中
            fileUploadInfo.setServerPath(absolutePath);
            fileUploadInfo.setExName("jpg");
            fileUploadInfo = dao.insert(fileUploadInfo);


            result.put("jpgPath",absolutePath);
            result.put("exName","jpg");
            result.put("width",width);
            result.put("height",height);
            result.put("fileName",fileName);
            result.put("fid",fileUploadInfo.getId());
            image.flush();
            image=null;

        }catch (Exception e){
            log.error(e.getCause(),e);
        }finally {
            if(document!=null){
                document.dispose();
                document = null;
            }
        }


        return result;
    }

    @Override

    public Map<String, Object> pdf2jpg_(String filePath) throws Exception {
        FileUploadInfo fileUploadInfo = new FileUploadInfo();

        Map<String, Object> result = new HashMap<>();
        try {
        float rotation = 0f;
        //缩略图显示倍数，1表示不缩放，0.5表示缩小到50%
        float zoom = 2.0f;

        document = new Document();
        document.setFile(filePath);

        BufferedImage image = (BufferedImage)document.getPageImage(0, GraphicsRenderingHints.SCREEN,
                Page.BOUNDARY_CROPBOX, rotation, zoom);
        RenderedImage rendImage = image;
        String thumbnailFileName =  getPath()+File.separator+System.currentTimeMillis()+".jpg";
        File thumbnailFile = new File(thumbnailFileName);
        ImageIO.write(rendImage, "jpg", thumbnailFile);

        int width = image.getWidth();
        int height = image.getHeight();


        String absolutePath = thumbnailFile.getAbsolutePath();

        // 将转化成的数据存到file表中
        fileUploadInfo.setServerPath(absolutePath);
        fileUploadInfo.setExName("jpg");
        fileUploadInfo = dao.insert(fileUploadInfo);


        result.put("jpgPath",absolutePath);
        result.put("exName","jpg");
        result.put("fid",fileUploadInfo.getId());
        image.flush();
        image=null;

    }catch (Exception e){
        log.error(e.getCause(),e);
    }finally {
            if(document!=null){
                document.dispose();
                document = null;
            }
        }

        return result;
    }


    @Override
    public Map<String, Object> upload_(String path) throws Exception{
       // FileUploadInfo fileUploadInfo = new FileUploadInfo();
        Map<String,Object> result = new HashMap<>();

        String suffix = Files.getSuffix(path);

        File f = new File(path);

        InputStream is = new FileInputStream(f);
        DataInputStream dataInputStream = new DataInputStream(is);

        String filePath = this.getPath();
        filePath+= R.UU16()+suffix;

        FileOutputStream fileOutputStream = new FileOutputStream(new File(filePath));
        ByteArrayOutputStream output = new ByteArrayOutputStream();

        byte[] buffer = new byte[1024];
        int length;

        while ((length = dataInputStream.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }
        byte[] context=output.toByteArray();
        fileOutputStream.write(output.toByteArray());
        dataInputStream.close();
        fileOutputStream.close();


        Long fileSize = new File(filePath).length();

        // 将转化成的数据存到file表中


        result.put("filePath",filePath);
        result.put("extName",suffix);
        result.put("fileSize",fileSize);
        //result.put("pfid",fileUploadInfo.getId());



        return result;
    }
    @Override
    public Map<String, Object> upload(String imgUrl) throws Exception{
        Map<String,Object> result = new HashMap<>();

        String suffix = Files.getSuffix(imgUrl);
        URL url =  new URL(imgUrl);

        DataInputStream dataInputStream = new DataInputStream(url.openStream());
        String path = url.getPath();
        System.out.println("path:"+path);
        String filePath = this.getPath();
        filePath+= R.UU16()+suffix;

        FileOutputStream fileOutputStream = new FileOutputStream(new File(filePath));
        ByteArrayOutputStream output = new ByteArrayOutputStream();

        byte[] buffer = new byte[1024];
        int length;

        while ((length = dataInputStream.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }
        byte[] context=output.toByteArray();
        fileOutputStream.write(output.toByteArray());
        dataInputStream.close();
        fileOutputStream.close();


        Long fileSize = new File(filePath).length();

        result.put("filePath",filePath);
        result.put("fileSize",fileSize);




        return result;
    }

    @Override
    public void deleteFile(Long fid) {
        FileUploadInfo fileUploadInfo = dao().fetch(FileUploadInfo.class, fid);
        if (fileUploadInfo!=null){
            String path = fileUploadInfo.getServerPath();
            Files.deleteFile(new File(path));
        }
    }

    @Override
    public Long base64ToJpg(String img) {
        try {
            byte[] b = Base64.getDecoder().decode(img);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {//调整异常数据
                    b[i] += 256;
                }
            }

            File tmpFile = tempFilePool.createFile(".jpg");
            //生成jpeg图片

            OutputStream out = new FileOutputStream(tmpFile);
            out.write(b);
            out.flush();
            out.close();
            //return true;


            List<Long> fileIds = this.migrationUploadFiles(tmpFile.getPath());


            return fileIds.get(0);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    public String getPath(){
        String filePath = properties.getFilepath();
        DateFormat df = new SimpleDateFormat("yyyyMM");
        String finderName = df.format(new Date());
        String path = filePath+File.separator+finderName+File.separator;
        File finderFile = new File(Disks.normalize(path));
        synchronized (finderFile){
            Files.createDirIfNoExists(finderFile);
        }
        return finderFile.getAbsolutePath()+File.separator;
    }

    public String getBasePath(){
        String filePath = properties.getFilepath();
       // DateFormat df = new SimpleDateFormat("yyyyMM");
        //String finderName = df.format(new Date());
        String path = filePath+File.separator;
        File finderFile = new File(Disks.normalize(path));
        synchronized (finderFile){
            Files.createDirIfNoExists(finderFile);
        }
        return finderFile.getAbsolutePath()+File.separator;
    }
}
